package com.yunc.user.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunc.common.core.result.R;
import com.yunc.common.web.aspect.AuthIgnore;
import com.yunc.user.sys.entity.SysDict;
import com.yunc.user.sys.service.ISysDictService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * 字典码
 *
 * @author congcong tao
 * @date 2018/11/19 17:09
 */
@RestController
@RequestMapping("sysDict")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SysDictController {

    private final ISysDictService sysDictService;

    @AuthIgnore
    @GetMapping("/page")
    public R page(Page<SysDict> page, SysDict sysDict) {
        QueryWrapper<SysDict> qw = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(sysDict.getName())) {
            qw.like("name", sysDict.getName());
        }
        sysDictService.page(page, qw);
        return R.ok().put("data", page.getRecords()).put("count", page.getTotal());
    }

    @GetMapping("/list")
    public R list(SysDict sysDict) {
        QueryWrapper<SysDict> ew = new QueryWrapper<>();
        List<SysDict> list = sysDictService.list(ew);
        return R.ok().put("list", list).put("sysDict", sysDict);
    }

    @GetMapping("/info/{id}")
    public R info(@PathVariable String id) {
        SysDict dict = sysDictService.getById(id);
        return R.ok().put("sysDict", dict);
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    public R save(@Validated SysDict dict) {
        dict.setCreateTime(new Date());
        boolean flag = sysDictService.save(dict);
        if (flag) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 修改
     */
    @PutMapping(value = "/update")
    public R update(@Validated SysDict dict) {
        // 级联删除或修改
        return sysDictService.updateDict(dict);
    }

    /**
     * 删除
     */
    @DeleteMapping("/delete/{ids}")
    public R delete(@PathVariable String ids) {
        return sysDictService.removeDict(ids);
    }
}
